package xlj.lib.android.base.view;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.util.AttributeSet;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by itufo on 2018/8/5.
 */

public class MyWebView extends android.webkit.WebView {
    private Context context;
    private HeadContentCallBack headContentCallBack;
    private Map<String,WebAction> actionMap = new HashMap<>();

    public void setHeadContentCallBack(HeadContentCallBack headContentCallBack) {
        this.headContentCallBack = headContentCallBack;
    }

    public void addWebAction(String tag,WebAction webAction) {
        actionMap.put(tag,webAction);
    }

    public MyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;

        init();
    }

    public MyWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;

        init();
    }

    public MyWebView(Context context) {
        super(context);
        this.context = context;

        init();
    }

    private void init(){
        if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.KITKAT) {
            setWebContentsDebuggingEnabled(true);
        }
        //js支持
        WebSettings settings = getSettings();
        settings.setJavaScriptEnabled(true);
        addJavascriptInterface(new InJavaScriptLocalObj(), "java_obj");
        //允许访问assets目录
        settings.setAllowFileAccess(true);
        //设置WebView排版算法, 实现单列显示, 不允许横向移动
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);

        //解决点击链接跳转浏览器问题
        setWebViewClient(new MyWebViewClient(this));

        setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder b = new AlertDialog.Builder(context);
                b.setTitle("Alert");
                b.setMessage(message);
                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                    }
                });
                b.setCancelable(false);
                b.create().show();
                return true;
            }
        });

    }

    private class MyWebViewClient extends WebViewClient {
        public MyWebViewClient(WebView webView) {
            //super(webView);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            for (String key : actionMap.keySet()) {
                if (url.startsWith(key)) {
                    WebAction webAction = actionMap.get(key);
                    if (webAction != null) {
                        webAction.onAction();
                    }
                    return true;
                }
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            view.loadUrl("javascript:window.java_obj.getHead('<head>'+" +
                    "document.getElementsByTagName('html')[0].innerHTML+'</head>');");
            super.onPageFinished(view, url);
        }
    }


    final class InJavaScriptLocalObj {
        @JavascriptInterface
        public void getHead(String html) {
            System.out.println("====>html="+html);
            Document document = Jsoup.parse(html);
            Element headElement = document.head();
            Elements elements = headElement.getElementsByTag("meta");
            if (elements != null && headContentCallBack != null) {
                headContentCallBack.onHeadElements(elements);
            }

        }
    }

    public interface HeadContentCallBack {
        void onHeadElements(Elements elements);
    }

    public interface WebAction {
        void onAction();
    }

}
